<template>
  <el-dialog v-dialogDrag v-if="popenevTVisible" title="请选择群组" :visible.sync="popenevTVisible" :before-close="handleCancel" width="850px" :close-on-click-modal="false">
    <div class="choice-group-box">
      <!-- 机构 -->
      <div class="org-list">
        <!-- 搜索框 -->
        <el-input class="org-search" placeholder="搜索" v-model="searchoOrgkey">
          <i slot="prefix" class="el-input__icon el-icon-search"></i>
        </el-input>
        <el-scrollbar class="scorll-Y">
          <el-tree class="filter-tree" :data="treeData" :props="{ label: 'orgCommonname' }" node-key="unid" :default-expanded-keys="expandedKey" :expand-on-click-node="false" :highlight-current="true" :check-on-click-node="true" :check-strictly="true" @check-change="handleOrgChange" :filter-node-method="filterOrgNode" ref="orgTree">
          </el-tree>
        </el-scrollbar>
      </div>
      <div class="group-list">
        <el-scrollbar class="scorll-Y">
          <el-tree class="filter-tree" :default-checked-keys="groupUnidArr" :show-checkbox="true" :data="groupList" :props="{ label: 'name' }" node-key="unid" :expand-on-click-node="false" :highlight-current="true" :check-on-click-node="true" :check-strictly="true" @check-change="handleGroupChange" ref="groupTree">
          </el-tree>
          <!-- <div class="group-item" v-for="(item,index) in gr"></div> -->
        </el-scrollbar>
      </div>
      <div class="group-list">
        <!-- <el-input v-model="personNameStr" disabled style="height:100%" type="textarea" /> -->
        <el-scrollbar class="scorll-Y">
          <div v-for="(pre_item, index) in personNameList" :key="index">
            <div>{{pre_item.name}}</div>
            <div v-for="(item, i) in pre_item.personName" :key="i" class="person-item">
              <span v-if="pre_item.personUnids">{{ item }} ({{ pre_item.personUnids[i] | formatOrg(pre_item.personList) }})</span>
              <span v-if="pre_item.personOrgs">{{ item }} ({{ pre_item.personOrgs[i] }})</span>
              <i class="btn-person-cacle el-icon-circle-close" @click="handleDelPerson(index, i)" />
            </div>
          </div>
        </el-scrollbar>
      </div>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="handleOk">确定</el-button>
      <el-button @click="handleCancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getOrgTree } from "../../api/system/organzation/api.js";
import { getList as getGroupList } from '../../api/module/systemGroup/systemGroup'
export default {
  data()
  {
    return {
      popenevTVisible: true,
      multiple: false,
      treeData: [], //机构列表
      groupList: [], //群组列表
      //promise 状态
      expandedKey: [],
      promiseStatus: null,
      searchoOrgkey: "", //机构搜索
      searchkey: "",
      parame: {
        organizationUnid: "",
      },
      replaceFields: {
        title: "name", key: "unid"
      },
      //人员名字字符串
      personNameStr: "",
      groupUnidArr: [],
      groupDataArr: [], //已选群组数据
      personNameList: []
    };
  },
  watch: {
    searchoOrgkey(val)
    {
      this.$refs.orgTree.filter(val);
    },
  },
  filters: {
    formatOrg(P_Unid, P_PersonList)
    {
      var item = P_PersonList.filter(v => v.unid == P_Unid)
      console.log(item, 'item')
      if (item.length > 0)
      {
        return item[0].personFullname.split('/')[1]
      }
      else
      {
        return ""
      }
    }
  },
  methods: {
    //过滤机构
    filterOrgNode(value, data)
    {
      if (!value) return true;
      return data[this.defaultProps.label].indexOf(value) !== -1;
    },
    show(showData, replaceFields, multiple, config)
    {
      //首先整理回显群组数据
      console.log(showData);
      if (showData && showData.constructor == Array)
      {
        this.groupDataArr = [...showData];
        this.groupDataArr.forEach(item =>
        {
          this.groupUnidArr.push(item.unid);
        })
        this.groupList = this.groupDataArr || [];
      }

      this.updataPersonName();

      this.getOrgTree();
      // this.getGroupList();
      this.multiple = multiple || false;
      this.replaceFields = replaceFields || this.replaceFields;


      // 创建promise
      return new Promise((resolve, reject) =>
      {
        this.promiseStatus = {
          resolve,
          reject,
        };
      });
    },
    handleOk()
    {
      let selects = this.groupDataArr;
      let tampPersonName = [];
      this.personNameList.forEach(item => {
        if (item.personName && item.personName.length > 0)
        {
          tampPersonName.push(item.name + "(" + item.personName.join(",") + ")")
        }
      })
      this.personNameStr = tampPersonName.join(",");

      this.promiseStatus.resolve({
        choiceData: selects,
        replaceFields: this.replaceFields,
        personNameStr: this.personNameStr
      });
      this.destroyElement();
    },
    handleCancel()
    {
      //清空勾选项
      this.promiseStatus.reject({
        msg: "取消",
      });

      this.destroyElement();
    },
    // 机构变化
    handleOrgChange(data, check, tree)
    {
      this.parame.organizationUnid = data.unid;
      this.getGroupList();
    },
    //获取机构
    getOrgTree()
    {
      getOrgTree().then((res) =>
      {
        this.treeData = res.result || [];
        this.treeData.forEach((element) =>
        {
          this.expandedKey.push(element.unid);
        });
      });
    },
    /**
     * 获取群组列表
     */
    getGroupList()
    {
      getGroupList(this.parame).then((res) =>
      {
        this.groupList = res.result.data || [];
      });
    },
    /**
     * 监听群组变化
     */
    handleGroupChange(data, check, tree)
    {
      if (check && !this.multiple)
      {
        this.$refs.groupTree.setCheckedKeys([data[unid]]);
      }
      this.groupDataArr = this.$refs.groupTree.getCheckedNodes();
      this.updataPersonName();

    },
    formatOrgs(P_Array)
    {
      var resultArr = []
      P_Array.map(item => {
        var orgname = item.split('/')[1]
        resultArr.push(orgname)
      })
      return resultArr;
    },
    //更新人员群组中的人员
    updataPersonName()
    {
      let tampPersonName = [];
      this.groupDataArr.forEach(item =>
      {
        if (item.persons && item.persons.commonNames && item.persons.commonNames.m_ArrayList)
        {
          // tampPersonName.push(item.name + "(" + item.persons.commonNames.m_ArrayList.join(",") + ")");
          tampPersonName.push({
            personName: item.persons.commonNames.m_ArrayList,
            personOrgs: this.formatOrgs(item.persons.fullNames.m_ArrayList),
            unid: item.unid,
            name: item.name
          })
        } else
        {
          // tampPersonName.push(item.name + "(" + item.personCommonnames + ")")
          tampPersonName.push({
            personName: item.personCommonnames.split(','),
            personUnids: item.personUnids.split(','),
            personList: item.personList,
            unid: item.unid,
            name: item.name
          })
        }
      })
      this.personNameList = tampPersonName
      this.personNameStr = tampPersonName.join(",");
    },
    // 删除人员
    handleDelPerson(P_Index, P_I)
    {
      this.personNameList[P_Index].personName.splice(P_I, 1)
    },
    /**
     * cs 2022-4-8
     * 销毁组件
     */
    destroyElement()
    {
      this.popenevTVisible = false;
    },
  },
};
</script>

<style lang="scss" scoped>
.choice-group-box {
  display: flex;
  .org-list {
    width: 300px;
    border: 1px solid #e6ebf5;
    border-radius: 4px;
    .org-search {
      width: 80%;
      margin: 20px 10px 0;
      height: 32px;
      ::v-deep .el-input__inner {
        border-radius: 100px;
      }
    }
  }
  .group-list {
    border: 1px solid #e6ebf5;
    border-radius: 4px;
    flex: 1;
    margin-left: 10px;
    ::v-deep .el-transfer {
      display: flex !important;
      align-items: center;
      .el-transfer__buttons {
        display: flex;
        padding: 0 10px;
        flex-direction: column-reverse;
        .el-button {
          margin: 10px 0;
          width: 70px;
          font-size: 12px;
          height: 30px;
          line-height: 1em;
          padding: 0;
          display: flex;
          align-items: center;
          justify-content: center;
        }
      }
    }

    .person-item {
      display: block;
      // height: 26px;
      // line-height: 26px;
      margin-bottom: 5px;
      padding-left: 25px;
    }
  }
}

.scorll-Y {
  height: 230px;
  margin-top: 10px;
  ::v-deep .el-scrollbar__wrap {
    overflow-x: hidden;
  }
}

::v-deep .el-textarea__inner {
  height: 100%;
}
</style>